package com.cby.code.base;

import android.app.Activity;

import com.cby.code.util.AppUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * DialogFragment堆栈管理类
 *
 * @author 陈宝阳
 * @create 2019/4/16
 */
public class UIStackManager {

    /**
     * Activity堆栈
     */
    private Map<String, BaseDialogFragment> fragmentMap = new HashMap<>();

    private UIStackManager() {
    }

    /**
     * 返回UIStackManager对象
     */
    public static UIStackManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final UIStackManager INSTANCE = new UIStackManager();
    }

    /**
     * 添加Fragment到堆栈中
     *
     * @param tag
     * @param fragment
     */
    public void addFragment(String tag, BaseDialogFragment fragment) {
        fragmentMap.put(tag, fragment);
    }

    /**
     * 移除指定tag的Fragment
     */
    public void removeFragment(String tag) {
        if (fragmentMap.containsKey(tag)) {
            fragmentMap.remove(tag);
        }
    }

    /**
     * 获取指定tag的Fragment
     */
    public BaseDialogFragment getFragment(String tag) {
        if (fragmentMap.containsKey(tag)) {
            return fragmentMap.get(tag);
        }
        return null;
    }

    /**
     * 判断是否有当前的tag的fragment对象
     *
     * @param tag String
     * @return Boolean
     */
    public Boolean hasFragment(String tag) {
        return fragmentMap.containsKey(tag);
    }

    /**
     * 结束指定的Fragment
     */
    public void finishFragment(String tag) {
        if (fragmentMap.containsKey(tag)) {
            BaseDialogFragment fragment = fragmentMap.remove(tag);
            fragment.dismiss();
        }
    }

    /**
     * 清理所有的Fragment
     */
    public void finishAllFragment() {
        for (Map.Entry<String, BaseDialogFragment> entry : fragmentMap.entrySet()) {
            if (!entry.getValue().isRemoving()) {
                entry.getValue().dismiss();
            }
        }
        fragmentMap.clear();
    }

    /**
     * 移除自己以外的Fragment
     */
    public void removeAboveFragments(String tag) {
        for (Map.Entry<String, BaseDialogFragment> entry : fragmentMap.entrySet()) {
            if (!entry.getValue().isRemoving() && !tag.equals(entry.getKey())) {
                entry.getValue().dismiss();
            }

        }
    }

    public int getSize() {
        return fragmentMap.size();
    }

    /**
     * 退出app
     */
    public void exitApp(Activity activity) {
        try {
            finishAllFragment();
            AppUtils.killAllProcess(activity);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

}